class UsersController < ApplicationController
  before_filter :login_required, :only=>[:edit, :update, :options, :save_options, :destroy, :delete, :deactivate, :editall]
  before_filter :find_user, :only=>[:show, :edit, :update, :options, :save_options, :delete, :deactivate, :editall, :edit_admin]
  before_filter :admin_required, :only=>[:edit_admin]
  
  def tag
  	@users = User.paginate_tagged_with(params[:id], :page=>params[:page], :per_page=>10, :order=>"created_at DESC")
  	@posts = Post.paginate_tagged_with(params[:id], :page=>params[:page], :per_page=>10, :order=>"created_at DESC")
  	@communities = Community.paginate_tagged_with(params[:id], :page=>params[:page], :per_page=>10, :order=>"created_at DESC")
  end
  
  # render new.rhtml
  def new
    @user = User.new
    @user.password = @user.password_confirmation = nil 
  end
  
  def update
  	@user.update_attributes!(params[:user])
		redirect_to user_path(@user)
  rescue ActiveRecord::RecordInvalid
    	render :action => 'edit'
  end
 
  def create
    logout_keeping_session!
    @user = User.new(params[:user])

    success = @user && @user.valid_with_captcha? && @user.save
    if success && @user.errors.empty?
      redirect_back_or_default('/')
      flash[:notice] = "Спасибо за регистрацию! Мы отправили Вам письмо с Вашим кодом активациии."
    else
      flash[:error]  = "We couldn't set up that account, sorry.  Please try again, or contact an admin (link is above)."
      render :action => 'new'
    end
  end

	def options
		@rss_channels = [current_user.rss_channels.new]
		@rss_channels_list = current_user.rss_channels
		@communities = current_user.communities.collect {|c| [c.title, community_posts_url(c, :format=>"rss")]}
	end
	
	def save_options
		@user.theme = params[:user][:theme]
		@user.is_context_menu = params[:user][:is_context_menu]
		@user.black_list = params[:user][:black_list]
		@user.save

		params[:rss_channel_attributes].each do |rss|
			unless rss[:url].blank?
			  @user.rss_channels.create(rss)
			end
		end if params[:rss_channel_attributes]
			
		redirect_to user_path(:id=>@user)
	end
	
  def activate
    logout_keeping_session!
    user = User.find_by_activation_code(params[:activation_code]) unless params[:activation_code].blank?
    case
    when (!params[:activation_code].blank?) && user && !user.active?
      user.activate!
      flash[:notice] = "Регистрация выполнена! Авторизируйтесь для продолжения."
      redirect_to '/login'
    when params[:activation_code].blank?
      flash[:error] = "The activation code was missing.  Please follow the URL from your email."
      redirect_back_or_default('/')
    else 
      flash[:error]  = "We couldn't find a user with that activation code -- check your email? Or maybe you've already activated -- try signing in."
      redirect_back_or_default('/')
    end
  end

  def destroy
  	user = User.find(current_user.id)
  	logout_killing_session!
		user.destroy
    flash[:notice] = "You have been deleted and logged out."
    redirect_back_or_default('/')
	end
  
  def deactivate
  	@user.activated_at = nil
  	@user.save
  	logout_killing_session!
  	flash[:notice] = "Ваш аккаунт заморожен";
		redirect_to root_path()
  end
  
  def edit_admin
  	@user.roles.clear
  	@user.roles << Role.find_by_ident(params[:admin] ?  Role::ADMIN  : Role::DEFAULT)
  	@user.save
  	render :update do |page| page.replace_html 'edit_admin', :partial => "edit_admin" end 
  end
  
  private
  
	def find_user
		login = params[:id].blank? ? request.host.downcase : params[:id]
		@user = User.find_by_login(login)
	end
	
	def authorized?
		['edit', 'update', 'options', 'save_options', 'destroy', 'delete', 'deactivate', 'editall', 'edit_admin'].include?(action_name)
	end
end
